<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Auto Popup</title>
  <style>
    /* 弹窗样式 */
  .popup {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 250px;
      height: 120px;
      background-color: #fff;
      border: 1px solid #ccc;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
      text-align: center;
      line-height: 120px;
      display: none;
    }
  </style>
</head>

<body>
  <div id="popup" class="popup">这是自动弹出的弹窗，无操作 5 秒自动关闭，有操作立即关闭</div>
  <script>
    // 获取弹窗元素
    const popup = document.getElementById('popup');

    // 页面加载完成后自动弹出弹窗
    window.addEventListener('load', function () {
      popup.style.display = 'block';

      // 记录上次操作时间
      let lastActivityTime = new Date().getTime();

      // 检查是否有操作的函数
      function checkActivity() {
        const currentTime = new Date().getTime();
        if (currentTime - lastActivityTime > 5000) {
          popup.style.display = 'none';
          clearInterval(activityCheckInterval);
        }
      }

      // 鼠标移动事件处理函数
      function handleMouseMove() {
        lastActivityTime = new Date().getTime();
      }

      // 键盘按下事件处理函数
      function handleKeyDown() {
        lastActivityTime = new Date().getTime();
      }

      // 监听鼠标移动和键盘按下事件
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('keydown', handleKeyDown);

      // 定期检查是否有操作的间隔
      const activityCheckInterval = setInterval(checkActivity, 1000);
    });
  </script>
</body>

</html>